<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules">
      <el-form-item label="等级名称" prop="levelName">
        <ns-input v-model="formData.levelName" placeholder="请输入等级名称" />
      </el-form-item>
      <!-- <el-form-item label="等级编号" prop="levelCode">
        <ns-input v-model="formData.levelCode" type="number" placeholder="请输入等级编号称" />
      </el-form-item> -->
      <el-form-item label="等级描述" prop="codeDesc">
        <ns-input v-model="formData.codeDesc" placeholder="请输入等级描述" />
      </el-form-item>
      <el-form-item label="重要程度" prop="importance">
        <el-select v-model="formData.importance" clearable placeholder="请选择重要程度">
          <el-option label="重要数据" value="重要数据" />
          <el-option label="公开数据" value="公开数据" />
        </el-select>
      </el-form-item>
      <el-form-item label="默认敏感期限" required prop="sensitiveDeadline">
        <el-radio-group v-model="formData.sensitiveDeadline">
          <el-radio label="3">永久</el-radio>
          <el-radio label="1">固定期限</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row>
        <el-form-item
          label="期限时间"
          required
          prop="deadlineTimeNum"
          v-if="formData.sensitiveDeadline === '1'"
        >
          <ns-input
            v-model="formData.deadlineTimeNum"
            clearable
            type="number"
            placeholder="请输入整数时长"
          />
        </el-form-item>
        <el-form-item required prop="deadlineTimeUnit" v-if="formData.sensitiveDeadline === '1'">
          <el-select
            v-model="formData.deadlineTimeUnit"
            placeholder="请选择时间单位"
            class="ml-12px flex-1"
            style="width: 200px"
          >
            <el-option
              v-for="item in timeUnitOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-row>

      <el-form-item
        label="到期后敏感级别"
        prop="deadlineLevel"
        required
        v-if="formData.sensitiveDeadline === '1'"
      >
        <el-select
          v-model="formData.deadlineLevel"
          placeholder="请选择"
          @change="deadlineLevelChange"
        >
          <el-option
            v-for="item in levelOptions"
            :key="item.value"
            :label="item.levelName"
            :value="item.levelCode"
          />
        </el-select>
      </el-form-item>
      <div class="mt-12px w-100% text-right" v-if="formData.sensitiveDeadline === '1'">
        <el-text>
          <el-icon>
            <Warning />
          </el-icon>
          审核通过“{{ formData.deadlineTimeNum
          }}{{ formData.deadlineTimeUnit }}”后，敏感级别自动变更为“{{ currentDeadLevel }}”
        </el-text>
      </div>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as LevelApi from '@/api/strategyManage/level'
import { Warning } from '@element-plus/icons-vue'
defineOptions({ name: 'LevelForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const timeUnitOptions = [
  {
    label: '年',
    value: '年'
  },
  {
    label: '月',
    value: '月'
  },
  {
    label: '日',
    value: '日'
  }
]
const currentDeadLevel = ref()

const levelOptions = ref([])
const formData = ref({
  id: undefined,
  levelName: undefined,
  levelCode: undefined,
  codeDesc: undefined,
  importance: undefined,
  sensitiveDeadline: undefined,
  deadlineTimeNum: undefined,
  deadlineTimeUnit: undefined,
  deadlineLevel: undefined
})
const formRules = reactive({
  levelName: [{ required: true, message: '等级名称不能为空', trigger: 'blur' }],
  // levelCode: [{ required: true, message: '等级编号不能为空', trigger: 'blur' }],
  importance: [{ required: true, message: '重要程度不能为空', trigger: ['blur', 'change'] }],
  sensitiveDeadline: [{ required: true, message: '敏感期限不能为空', trigger: 'blur' }],
  deadlineTimeNum: [{ required: true, message: '时长不能为空', trigger: 'blur' }],
  deadlineTimeUnit: [{ required: true, message: '时间单位不能为空', trigger: 'blur' }],
  deadlineLevel: [{ required: true, message: '到期后敏感级别不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await LevelApi.levelGet(id)
      formData.value = data
      formData.value.deadlineLevel = Number(data.deadlineLevel)
    } finally {
      formLoading.value = false
    }
  }
  getLevelOptions()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const getLevelOptions = async () => {
  const data = await LevelApi.levelPage({ pageSize: 9999, pageNum: 1 })
  levelOptions.value = data.data
  const current = levelOptions.value.find((item) => item.levelCode == formData.value.deadlineLevel)
  currentDeadLevel.value = current.levelName
}

const deadlineLevelChange = (e) => {
  const current = levelOptions.value.find((item) => item.levelCode == formData.value.deadlineLevel)
  currentDeadLevel.value = current.levelName
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await LevelApi.levelCreate(data)
      message.success(t('common.createSuccess'))
    } else {
      await LevelApi.levelUpdate(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    levelName: undefined,
    levelCode: undefined,
    codeDesc: undefined,
    importance: undefined,
    sensitiveDeadline: undefined,
    deadlineTimeNum: undefined,
    deadlineTimeUnit: undefined,
    deadlineLevel: undefined
  }
  formRef.value?.resetFields()
}
</script>
